package business.facade;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.swing.text.DefaultEditorKit.BeepAction;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

import util.DynamicObjectHandler;
import util.ServerResponse;
import util.SessionFactorySingleton;
import util.WordReader;
import business.bl.BasicOperation;
import business.dto.CandidatoDTO;
import business.dto.GestioneCandidatoDTO;
import entities.CandidatoEntity;
import entities.FormElementEntity;
import entities.GestioneCandidatoEntity;

public class CandidatoFacade implements BasicOperation{
	public static Logger logger = LogManager.getLogger(CandidatoFacade.class);
	
	private String contextPath="";
	
	@Override
	public ServerResponse save(HashMap parametersList) throws Exception {
		logger.info("BEGIN - CandidatoFacade - save");
		String servletName = (String) parametersList.get("servletName");
	     

        String serverResponseMessage="OK";
        ServerResponse returnValue = new ServerResponse(servletName, null, serverResponseMessage);
        
        HttpServletRequest request=(HttpServletRequest)parametersList.get("request");
                
        String name = request.getParameter("name");
       
        String id= request.getParameter("id");

        Map parameterMap = request.getParameterMap();
        Set keySet = parameterMap.keySet();
        
        Iterator it = keySet.iterator();
        
        HashMap<String, String> candidatoParameter=new HashMap<String, String>();
        
//      StringBuffer customFields=new StringBuffer();
      while (it.hasNext())
      {
          String key = (String) it.next();
          String value = (String) request.getParameter(key);
          logger.debug(value);
          candidatoParameter.put(key, value);
      }
        
        
//         name=(parameterMap.get("name")).toString();
        
        
//	    String method = request.getParameter("method");   
        
        
        try {
        	SessionFactory sessionFactory = SessionFactorySingleton.getInstance().getSesssionFactory();
		    logger.info("istanziato il session factory");
		    
		    DynamicObjectHandler doh=new DynamicObjectHandler();
		    
		    
		    
		    
		    Session session = sessionFactory.openSession();
		    
		    CandidatoEntity ce=new CandidatoEntity();
		    CandidatoDTO cDTO=new CandidatoDTO();

		    if(id.equals("null")){
		   		doh.fill(cDTO, candidatoParameter);
			    doh.fill(ce, cDTO);
		    	ce.setDateTime(new Date());
		    	
		    	Date d=new Date();
        		String dataNascita=candidatoParameter.get("dataNascita");
		    	
        		ResourceBundle rb= ResourceBundle.getBundle("bundle");
    			String dateFormat=rb.getString("DATE_FORMAT");
    			
        		SimpleDateFormat sdf=new SimpleDateFormat(dateFormat);
        		
		    	
        		try{
        			if(dataNascita!=null){
        				d=sdf.parse(dataNascita);
            			ce.setDataNascita(d);
            		}else{
            			ce.setDataNascita(null);
            		}
        		} catch (java.text.ParseException e) {
    				logger.error(e); 
    			}
        		
		    	
		    	
		    	Transaction transaction = session.beginTransaction();
		    	session.merge(ce);
		    
		    	transaction.commit();
		    	
		    	
		    }else{
		    	doh.fill(cDTO, candidatoParameter);
		    	 List <CandidatoEntity> fromDb = (List<CandidatoEntity>) session.createCriteria(CandidatoEntity.class)
			    	.add(Restrictions.eq( "id", new Integer(id))).list();
			    
				   	
			
				ce=fromDb.get(0);
				doh.update(ce, cDTO);
		    	
//				GestioneCandidatoEntity gce=new GestioneCandidatoEntity();
//				
//				if(ce.getGestioneCandidato()!=null){
//					gce=ce.getGestioneCandidato();
//				}
////				
//				GestioneCandidatoDTO gcDTO=new GestioneCandidatoDTO();
////				
//				doh.fill(gcDTO, candidatoParameter);
//				doh.update(gcDTO,gce );
//				gce.setId(new Integer(id));
//				ce.setGestioneCandidato(gce);
				
				Date d=new Date();
				
				
        		
        		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        		
        		String dataNascita =candidatoParameter.get("dataNascita");
        		
        		try{
        			if(dataNascita!=null){
            			d=sdf.parse(dataNascita);
            			ce.setDataNascita(d);
            		}else{
            			ce.setDataNascita(null);
            		}
        		} catch (java.text.ParseException e) {
    				logger.error(e); 
    			}
        		
        		
        		
        		
		    	
		    	
		    	
				
				
				
				Transaction transaction = session.beginTransaction();
		    	session.merge(ce);
		    
		    	transaction.commit();
		    }
		    
		    session.flush();
		    
		   	session.close();
		   	
		   	returnValue.setResponseMessage("Candidato "+name+" salvato correttamente");
		   	
		   	
		    
		} catch (Throwable ex) {
		    // Log the exception.
		    logger.error("Initial SessionFactory creation failed.", ex); 
		    returnValue.setResponseMessage("KO");
			returnValue.setResponseMessage("Salvataggio del candidato fallito");
		}
        
		logger.info("END - CandidatoFacade - save");
        return returnValue;
	}
	
	
	public ServerResponse find(HashMap parametersList) throws Exception {
		logger.info("BEGIN - CandidatoFacade - find");
		String servletName = (String) parametersList.get("servletName");
		
		String ricercaSuFile = (String) parametersList.get("ricercaSuFile");
		String textToSearch = (String) parametersList.get("textToSearch");
		
		String dateStart1 = (String) parametersList.get("dateStart1");
		String dateStart2 = (String) parametersList.get("dateStart2");


        String serverResponseMessage="OK";
        ServerResponse returnValue = new ServerResponse(servletName, null, serverResponseMessage);
        
        HttpServletRequest request=(HttpServletRequest)parametersList.get("request");
        
        ServletContext servletContext=(ServletContext)parametersList.get("servletContext");
        
        contextPath=servletContext.getRealPath("/temp_files");
        
        Map parameterMap = request.getParameterMap();
        Set keySet = parameterMap.keySet();
        
        boolean simpleSearch=false;
        
        boolean dateSearch=false;
        
        Iterator it = keySet.iterator();
        
        HashMap<String, String> candidatoParameter=new HashMap<String, String>();
        
//      StringBuffer customFields=new StringBuffer();
        while (it.hasNext()){
	      String key = (String) it.next();
	      String value = (String) request.getParameter(key);
	      logger.debug(value);
	      candidatoParameter.put(key, value);
        }
        
        
        
     // SessionFactory from standard hibernate.cfg.xml file
		try {
			SessionFactory sessionFactory = SessionFactorySingleton.getInstance().getSesssionFactory();
		    logger.info("istanziato il session factory");
		    
		    Session session = sessionFactory.openSession();
		    
		    List <CandidatoEntity> fromDb = new ArrayList<CandidatoEntity>();
		    
		    Criteria criteria =	session.createCriteria(CandidatoEntity.class);
		    Disjunction or = Restrictions.disjunction();
		    Conjunction between = Restrictions.conjunction();
		    
		    candidatoParameter.remove("servletContext");
	    	
		    candidatoParameter.remove("target");
		    candidatoParameter.remove("method");
		    candidatoParameter.remove("action");
		    
		    
		    candidatoParameter.remove("logout");
		    candidatoParameter.remove("find");
		    
		    candidatoParameter.remove("ricercaSuFile");
		    candidatoParameter.remove("textToSearch");
		    
		    candidatoParameter.remove("dateStart1");
		    candidatoParameter.remove("dateStart2");
		    
		    
		    ArrayList<String> parameterNames=new ArrayList<String>(candidatoParameter.keySet());
		    ArrayList<String> parameterValues=new ArrayList<String>(candidatoParameter.values());
		    
			// BEGIN - CONTROLLO RICERCA ESCLUSIVA
		    
		    if(ricercaSuFile!="1" && !candidatoParameter.isEmpty()){
		    	for(int i=0;i<parameterNames.size();i++){
			    	String parameterName=parameterNames.get(i);
			    	String parameterValue=parameterValues.get(i);
			    	
			    	
			    	or.add(Restrictions.ilike(parameterName, parameterValue));
			    	
			    }
		    	simpleSearch=true;
		    	criteria.add(or);
		    	
		    }
		    
		    
		    if(dateStart1!=null && dateStart2!=null){
		    	// 	BEGIN CONTROLLO SU DATE DI RICERCA
		    	
		    	Date d1=new Date();
		    	Date d2=new Date();
		    	
		    	ResourceBundle rb= ResourceBundle.getBundle("bundle");
				String dateFormat=rb.getString("DATE_FORMAT");
				
	    		SimpleDateFormat sdf=new SimpleDateFormat(dateFormat);
        		
        		try{
        			if(dateStart1!=null && dateStart2!=null){
            			d1=sdf.parse(dateStart1);
            			d2=sdf.parse(dateStart2);
            			
            			between.add(Restrictions.between("dateStart", d1, d2));
            			
            			criteria.add(between);
            			
            		}
        		} catch (java.text.ParseException e) {
    				logger.error(e); 
    			}
        		
        		dateSearch=true;
        		
		     	//  END CONTROLLO SU DATE DI RICERCA
		    }
		    
		    if(dateSearch==true || simpleSearch==true){
		    	criteria.addOrder(Property.forName("dateStart").desc());
		    	
		    	fromDb= (List<CandidatoEntity>)criteria.list();
			   	
			   	for (int i = 0; i < fromDb.size(); i++) {
			   		CandidatoDTO ceDTO=fromDb.get(i).getDTO();
			   		returnValue.addData(ceDTO);
				}
			   	session.flush();
		    }
		   	
		 // END - CONTROLLO RICERCA ESCLUSIVA
		   	
		   	
		   	// BEGIN - INSERIMENTO DATI ALTERNATIVI PER FILTRO RICERCA
		    if(textToSearch!=null){
		    	textToSearch=textToSearch.trim();
		    }
		    
		    
		   	candidatoParameter.put("textToSearch",textToSearch);
		   	candidatoParameter.put("checkSearch",ricercaSuFile);
		   	
		   	candidatoParameter.put("dateStart1",dateStart1);
		   	candidatoParameter.put("dateStart2",dateStart2);
		   
		   	ServerResponse sr=create(candidatoParameter);
		   	returnValue.setAlternativedata(sr.getData());
		   	
			// END - INSERIMENTO DATI ALTERNATIVI PER FILTRO RICERCA
		   	
			if(ricercaSuFile!=null && textToSearch!=null){
				
				if(ricercaSuFile.equals("1")){
					ArrayList<Object> retrievedFiles=ricercaSuFile(list(new HashMap()).getData(),new StringBuffer(textToSearch));
			   		
					
					
			   		if(returnValue.getData()==null){
			   			returnValue.setData(retrievedFiles);
			   		}else{
			   			
			   		// BEGIN CONTROLLO DI RIDONDANZA RECORD RECUPERATI
						
						ArrayList list=new ArrayList(returnValue.getData());
						
						list.addAll(retrievedFiles);
						
						Set set=new HashSet();
						
						for(int i=0;i<list.size();i++){
							set.add(list.get(i));
						}
						
						ArrayList retrievedElements=new ArrayList(set) ;
						
					// END CONTROLLO DI RIDONDANZA RECORD RECUPERATI
			   			
			   			returnValue.setData(retrievedElements);
			   		}
				}
				
		   		
		   		
		   		
		   		
		   	}
		    
		} catch (Throwable ex) {
		    // Log the exception.
		    logger.error("Initial SessionFactory creation failed.", ex);
		    returnValue.setResponseMessage("KO");
		    returnValue.setResponseMessage("Recupero della lista Candidati fallito");
		}
        
        logger.info("END - CandidatoFacade - find");
        return returnValue;
	}
	
	
	public Integer getNewCVElements(){
		logger.info("BEGIN - CandidatoFacade - getNewCVElements");
		Integer returnValue=new Integer(0);
		
		try {
			SessionFactory sessionFactory = SessionFactorySingleton.getInstance().getSesssionFactory();
		    logger.info("istanziato il session factory");
		    
		    
		    Session session = sessionFactory.openSession();
		    Criteria criteria=session.createCriteria(CandidatoEntity.class);
		    criteria.add(Restrictions.eq( "incoming", true));
		    
		    returnValue = criteria.list().size();
		    

		   	session.flush();
		   	
		   	CandidatoDTO candidatoFilterDTO =new CandidatoDTO();
		   
		    
		} catch (Throwable ex) {
		    // Log the exception.
		    logger.error("Errore nel recupero dei nuovi candidati", ex);
		    
		}
		
		
		logger.info("END - CandidatoFacade - getNewCVElements");
		return returnValue;
	}
	
	public ServerResponse listIncoming(HashMap parametersList) throws Exception {
		logger.info("BEGIN - listIncoming - list");
		String servletName = (String) parametersList.get("servletName");
	     

        String serverResponseMessage="OK";
        ServerResponse returnValue = new ServerResponse(servletName, null, serverResponseMessage);
        
     // SessionFactory from standard hibernate.cfg.xml file
		try {
			SessionFactory sessionFactory = SessionFactorySingleton.getInstance().getSesssionFactory();
		    logger.info("istanziato il session factory");
		    
		    
		    Session session = sessionFactory.openSession();
		    Criteria criteria=session.createCriteria(CandidatoEntity.class);
		    criteria.add(Restrictions.eq("incoming",true));
		    
		    List<CandidatoEntity> fromDb = criteria.list();
		    
//		    String hql = "from CandidatoEntity";
//		   	Query query = session.createQuery(hql); 
		   	
		    //	BEGIN CODIFICA DEI CAMPI DI FABRIK
		    
		    criteria=session.createCriteria(FormElementEntity.class);
		    criteria.add(Restrictions.eq( "name", "contratto"));
		    
		    FormElementEntity feeContratto=new FormElementEntity();
		    feeContratto=(FormElementEntity)criteria.uniqueResult();
		    
		   	session.flush();
		   	
		   	FormElementEntity feeSkill=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "skill"));
		   			   	
		   	feeSkill=(FormElementEntity)criteria.uniqueResult();
		   	session.flush();
		   	
		    //	END CODIFICA DEI CAMPI DI FABRIK
		   	
		   	for (int i = 0; i < fromDb.size(); i++) {
		   		CandidatoDTO ceDTO=fromDb.get(i).getDTO();
		   					   	
			   	ceDTO.setContratto(feeContratto.getDTO().toString(ceDTO.getContratto()));
			   	ceDTO.setSkill(feeSkill.getDTO().toString(ceDTO.getSkill()));
		   		
		   		returnValue.addData(ceDTO);
			}
		   	session.flush();
		   	
		   	// BEGIN - INSERIMENTO DATI ALTERNATIVI PER FILTRO RICERCA
		   	
		   	CandidatoDTO candidatoFilterDTO =new CandidatoDTO();
		   	
		   
		   	
		   	ServerResponse sr=create(parametersList);
		   	
		   	returnValue.setAlternativedata(sr.getData());
		   	
			// END - INSERIMENTO DATI ALTERNATIVI PER FILTRO RICERCA
		   	
		   	
		    
		} catch (Throwable ex) {
		    // Log the exception.
		    logger.error("Initial SessionFactory creation failed.", ex);
		    returnValue.setResponseMessage("KO");
		    returnValue.setResponseMessage("Recupero della lista Candidati fallito");
		}
        
        logger.info("END - CandidatoFacade - list");
        return returnValue;
	}
	@Override
	public ServerResponse list(HashMap parametersList) throws Exception {
		logger.info("BEGIN - CandidatoFacade - list");
		String servletName = (String) parametersList.get("servletName");
	     

        String serverResponseMessage="OK";
        ServerResponse returnValue = new ServerResponse(servletName, null, serverResponseMessage);
        
     // SessionFactory from standard hibernate.cfg.xml file
		try {
			SessionFactory sessionFactory = SessionFactorySingleton.getInstance().getSesssionFactory();
		    logger.info("istanziato il session factory");
		    
		    
		    Session session = sessionFactory.openSession();
		    Criteria criteria=session.createCriteria(CandidatoEntity.class);
		    criteria.addOrder(Property.forName("dateStart").desc());
		    
		    List<CandidatoEntity> fromDb = criteria.list();
		    
//		    String hql = "from CandidatoEntity";
//		   	Query query = session.createQuery(hql); 
		   	
		    //	BEGIN CODIFICA DEI CAMPI DI FABRIK
		    
		    criteria=session.createCriteria(FormElementEntity.class);
		    criteria.add(Restrictions.eq( "name", "contratto"));
		    
		    FormElementEntity feeContratto=new FormElementEntity();
		    feeContratto=(FormElementEntity)criteria.uniqueResult();
		    
		   	session.flush();
		   	
		   	FormElementEntity feeSkill=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "skill"));
		   			   	
		   	feeSkill=(FormElementEntity)criteria.uniqueResult();
		   	session.flush();
		   	
		    //	END CODIFICA DEI CAMPI DI FABRIK
		   	
		   	for (int i = 0; i < fromDb.size(); i++) {
		   		CandidatoDTO ceDTO=fromDb.get(i).getDTO();
		   					   	
			   	ceDTO.setContratto(feeContratto.getDTO().toString(ceDTO.getContratto()));
			   	ceDTO.setSkill(feeSkill.getDTO().toString(ceDTO.getSkill()));
		   		
		   		returnValue.addData(ceDTO);
			}
		   	session.flush();
		   	
		   	// BEGIN - INSERIMENTO DATI ALTERNATIVI PER FILTRO RICERCA
		   	
		   	CandidatoDTO candidatoFilterDTO =new CandidatoDTO();
		   	
		   
		   	
		   	ServerResponse sr=create(parametersList);
		   	
		   	returnValue.setAlternativedata(sr.getData());
		   	
			// END - INSERIMENTO DATI ALTERNATIVI PER FILTRO RICERCA
		   	
		   	
		    
		} catch (Throwable ex) {
		    // Log the exception.
		    logger.error("Initial SessionFactory creation failed.", ex);
		    returnValue.setResponseMessage("KO");
		    returnValue.setResponseMessage("Recupero della lista Candidati fallito");
		}
        
        logger.info("END - CandidatoFacade - list");
        return returnValue;
	}

	@Override
	public ServerResponse delete(HashMap parametersList) throws Exception {
		logger.info("BEGIN - CandidatoFacade - delete");
		String servletName = (String) parametersList.get("servletName");
	     

        String serverResponseMessage="OK";
        ServerResponse returnValue = new ServerResponse(servletName, null, serverResponseMessage);
        
        HttpServletRequest request=(HttpServletRequest)parametersList.get("request");
                
        String id= request.getParameter("id");

        try {
		    SessionFactory sessionFactory = SessionFactorySingleton.getInstance().getSesssionFactory();
		    logger.info("istanziato il session factory");
		    
		    
		    
		    
		    Session session = sessionFactory.openSession();
		    
		    CandidatoEntity ce=new CandidatoEntity();
		 
		    Transaction transaction= session.beginTransaction();
		    if(id!=null){
		    	ce.setId(new Integer(id));
		    	session.delete(ce);
		    	session.flush();
		    }
		    transaction.commit();
		   	session.close();
		   	
		   	returnValue.setResponseMessage("Candidato con id "+id+" cancellato correttamente");
		   	
		   	
		    
		} catch (Throwable ex) {
		    // Log the exception.
		    logger.error("Initial SessionFactory creation failed.", ex); 
		    returnValue.setResponseMessage("KO");
			returnValue.setResponseMessage("Eliminazione del candidato fallito");
		}
        
		logger.info("END - CandidatoFacade - delete");
        return returnValue;
	}

	@Override
	public ServerResponse load(HashMap parametersList) throws Exception {
		
		logger.info("BEGIN - CandidatoFacade - load");
		String servletName = (String) parametersList.get("servletName");
	     

        String serverResponseMessage="OK";
        ServerResponse returnValue = new ServerResponse(servletName, null, serverResponseMessage);
        
        HttpServletRequest request=(HttpServletRequest)parametersList.get("request");
                
        String id = request.getParameter("id");
       
        
        
        try {
        	SessionFactory sessionFactory = SessionFactorySingleton.getInstance().getSesssionFactory();
		    logger.info("istanziato il session factory");
		    		    
		    Session session = sessionFactory.openSession();
		    
		    CandidatoEntity candidatoEntity = (CandidatoEntity) session.createCriteria(CandidatoEntity.class)
	    	.add(Restrictions.eq( "id", new Integer(id))).uniqueResult();

		    
		    candidatoEntity.setIncoming(false);
		    
		    Transaction transaction = session.beginTransaction();
	    	session.merge(candidatoEntity);
	    
	    	transaction.commit();
		    session.flush();
		    
		    
		    FormElementEntity feeContratto=new FormElementEntity();
		   	
		   	Criteria criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "contratto"));
		   			   	
		   	feeContratto=(FormElementEntity)criteria.uniqueResult();
		   	session.flush();
		    
		   	FormElementEntity feeSkill=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "skill"));
		   			   	
		   	feeSkill=(FormElementEntity)criteria.uniqueResult();
		   	session.flush();
	
		   	FormElementEntity feeAmbientiSvil=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "ambienti_svil"));
		   	
		   	feeAmbientiSvil=(FormElementEntity)criteria.uniqueResult();
		   	
		   	
		    session.flush();
		   	FormElementEntity feeSistemiOperativi=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "sistemi_operativi"));
		   	
//		   	List <FormElementEntity> skills = (List<FormElementEntity>)criteria.list();
		   	
		   	feeSistemiOperativi=(FormElementEntity)criteria.uniqueResult();
		   	
		   	session.flush();
		   	FormElementEntity feeDB=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "db"));
		   			   	
		   	feeDB=(FormElementEntity)criteria.uniqueResult();
		   	
		   	
		   	session.flush();
		   	FormElementEntity feeAppServer=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "app_server"));
		   	   	
		   	feeAppServer=(FormElementEntity)criteria.uniqueResult();
		   	
		   	session.flush();
		   	FormElementEntity feeProdotti=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "prodotti"));
		   	
		   	feeProdotti=(FormElementEntity)criteria.uniqueResult();
		   	
		   	session.flush();
		   	FormElementEntity feeLingue=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "lingue"));
		   	
		   	feeLingue=(FormElementEntity)criteria.uniqueResult();
		   	
		   	session.flush();
		   	FormElementEntity feePatente=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "patente"));
		   	
		   	feePatente = (FormElementEntity)criteria.uniqueResult();
		   	
		   	session.flush();
		   	FormElementEntity feeCCHC = new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "come_ci_hai_conosciuto"));
		   	
		   	
		   	feeCCHC=(FormElementEntity)criteria.uniqueResult();
		   	
		  
//		   	logger.debug("------- ambiente svil: "+feeAmbientiSvil.getDTO().toString(""));
		   	
		
	   		CandidatoDTO ceDTO=candidatoEntity.getDTO();
	   		
	   		ceDTO.setContratto(feeContratto.getDTO().toString(ceDTO.getContratto()));
	   		ceDTO.setSkill(feeSkill.getDTO().toString(ceDTO.getSkill()));
	   		ceDTO.setAmbientiSvil(feeAmbientiSvil.getDTO().toString(ceDTO.getAmbientiSvil()));
	   		ceDTO.setSistemiOperativi(feeSistemiOperativi.getDTO().toString(ceDTO.getSistemiOperativi()));
	   		ceDTO.setDb(feeDB.getDTO().toString(ceDTO.getDb()));
	   		ceDTO.setAppServer(feeAppServer.getDTO().toString(ceDTO.getAppServer()));
	   		ceDTO.setProdotti(feeProdotti.getDTO().toString(ceDTO.getProdotti()));	
	   		ceDTO.setLingue(feeLingue.getDTO().toString(ceDTO.getLingue()));
	   		ceDTO.setPatente(feePatente.getDTO().toString(ceDTO.getPatente()));
	   		ceDTO.setComeCiHaiConosciuto(feeCCHC.getDTO().toString(ceDTO.getComeCiHaiConosciuto()));
	   		
	   		returnValue.addData(ceDTO);
		
	   	
		   	
		    
		} catch (Throwable ex) {
		    // Log the exception.
		    logger.error("Initial SessionFactory creation failed.", ex); 
		    returnValue.setResponseMessage("KO");
			returnValue.setResponseMessage("Caricamento del candidato fallito");
		}
        
		logger.info("END - CandidatoFacade - load");
		
        return returnValue;
		
	}

	@Override
	public ServerResponse upload(HashMap parametersList) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ServerResponse create(HashMap parametersList) throws Exception {
		
		logger.info("BEGIN - CandidatoFacade - create");
		String servletName = (String) parametersList.get("servletName");
	     

        String serverResponseMessage="OK";
        ServerResponse returnValue = new ServerResponse(servletName, null, serverResponseMessage);
        
        try {
        	SessionFactory sessionFactory = SessionFactorySingleton.getInstance().getSesssionFactory();
		    logger.info("istanziato il session factory");
		    		    
		    Session session = sessionFactory.openSession();
		    
		   

		   	FormElementEntity feeSkill=new FormElementEntity();
		   	

		   	Criteria criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "contratto"));
		   			   	
		   	
		   	FormElementEntity feeContratto=new FormElementEntity();
		   	feeContratto=(FormElementEntity)criteria.uniqueResult();
		   	
		   	
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "skill"));
		   	

		   	
		   	feeSkill=(FormElementEntity)criteria.uniqueResult();
	
		   	
		   	FormElementEntity feeAmbientiSvil=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "ambienti_svil"));
		   	
		   	feeAmbientiSvil=(FormElementEntity)criteria.uniqueResult();
		   	
		   	
		    session.flush();
		   	FormElementEntity feeSistemiOperativi=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "sistemi_operativi"));
		   	

		   	
		   	feeSistemiOperativi=(FormElementEntity)criteria.uniqueResult();
		   	
		   	
		   	session.flush();
		   	FormElementEntity feeDB=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "db"));
		   	

		   	
		   	feeDB=(FormElementEntity)criteria.uniqueResult();
		   	
		   	session.flush();
		   	FormElementEntity feeAppServer=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "app_server"));
		   	
		   	
		   	feeAppServer=(FormElementEntity)criteria.uniqueResult();
		   	
		
			session.flush();
		   	FormElementEntity feeProdotti=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "prodotti"));
		   	
		   	
		   	feeProdotti=(FormElementEntity)criteria.uniqueResult();
		   	
		   	session.flush();
		   	FormElementEntity feeLingue=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "lingue"));
		   	
		   	feeLingue=(FormElementEntity)criteria.uniqueResult();
		   	
		   	session.flush();
		   	FormElementEntity feePatente=new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "patente"));
		   	
		   	feePatente = (FormElementEntity)criteria.uniqueResult();
		   	
		   	session.flush();
		   	FormElementEntity feeCCHC = new FormElementEntity();
		   	
		   	criteria=session.createCriteria(FormElementEntity.class);
		   	criteria.add(Restrictions.eq( "name", "come_ci_hai_conosciuto"));
		   	
		   	
		   	feeCCHC=(FormElementEntity)criteria.uniqueResult();
		   	
		   	DynamicObjectHandler doh=new DynamicObjectHandler();
	   		CandidatoDTO ceDTO=new CandidatoDTO();
	   		
	   		doh.fill(ceDTO, parametersList);
	   		
	   		String dateStart1=(String) parametersList.get("dateStart1");
	   		String dateStart2=(String) parametersList.get("dateStart2");
	   		
	   		Date d1=new Date();
	   		Date d2=new Date();
    		
    		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    		
    		if(dateStart1!=null && dateStart2!=null){
    			d1=sdf.parse(dateStart1);
        		d2=sdf.parse(dateStart2);
    	   		
    	   		ceDTO.setDateStart1(d1);
    	   		ceDTO.setDateStart2(d2);
    		}
    		
    		
    		ceDTO.setContratto(feeContratto.getDTO().toString(ceDTO.getContratto()));
	   		ceDTO.setSkill(feeSkill.getDTO().toString(ceDTO.getSkill()));
	   		ceDTO.setAmbientiSvil(feeAmbientiSvil.getDTO().toString(ceDTO.getAmbientiSvil()));
	   		ceDTO.setSistemiOperativi(feeSistemiOperativi.getDTO().toString(ceDTO.getSistemiOperativi()));
	   		ceDTO.setDb(feeDB.getDTO().toString(ceDTO.getDb()));
	   		ceDTO.setAppServer(feeAppServer.getDTO().toString(ceDTO.getAppServer()));	
	   		ceDTO.setProdotti(feeProdotti.getDTO().toString(ceDTO.getProdotti()));	
	   		ceDTO.setLingue(feeLingue.getDTO().toString(ceDTO.getLingue()));
	   		ceDTO.setPatente(feePatente.getDTO().toString(ceDTO.getPatente()));
	   		ceDTO.setComeCiHaiConosciuto(feeCCHC.getDTO().toString(ceDTO.getComeCiHaiConosciuto()));
	   		
		   	returnValue.addData(ceDTO);
			
		   	
		   	
		    
		} catch (Throwable ex) {
		    // Log the exception.
		    logger.error("Initial SessionFactory creation failed.", ex); 
		    returnValue.setResponseMessage("KO");
			returnValue.setResponseMessage("Caricamento del form fallito");
		}
        
		logger.info("END - CandidatoFacade - create");
        return returnValue;
	}
	
	private ArrayList<Object> ricercaSuFile(ArrayList candidatoList, StringBuffer text) {
		logger.info("END - CandidatoFacade - ricercaSuFile");
		ArrayList returnValue =new ArrayList();
		
		ResourceBundle rb= ResourceBundle.getBundle("bundle");
		
		String joomlaHost =rb.getString("JOOMLA_HOST");
		
		int searchedTextIndex=-1;
		WordReader wr=null;
		for(int i=0;i<candidatoList.size();i++){
			CandidatoDTO candidatoDTO=(CandidatoDTO)candidatoList.get(i);
			
			logger.info("candidatoDTO.getCv() - "+joomlaHost+candidatoDTO.getCv());
			
			URL url;
			if(candidatoDTO.getCv()!=null){
				int slashPosition= candidatoDTO.getCv().lastIndexOf("/");
				
				String fileName= candidatoDTO.getCv().substring(slashPosition+1,candidatoDTO.getCv().length());
				try {
					url = new URL(joomlaHost+candidatoDTO.getCv());
					
					// BEGIN RECUPERO FILE REMOTO E SALVATAGGIO TEMPORANEO IN LOCALE
				
					FileOutputStream outputStream = 
		                new FileOutputStream(new File(contextPath+"/"+fileName));
					
					URLConnection uc = url.openConnection();
				    String contentType = uc.getContentType();
				    int contentLength = uc.getContentLength();
					
					InputStream raw = uc.getInputStream();
				    InputStream in  = new BufferedInputStream(raw);
				    byte[] data = new byte[contentLength];
				    int bytesRead = 0;
				    int offset = 0;
				    while (offset < contentLength) {
				       bytesRead = in.read(data, offset, data.length-offset);
				       if (bytesRead == -1) break;
				       offset += bytesRead;
				    }
				    in.close();
				    
				    if (offset != contentLength) {
				      throw new IOException("Only read " + offset 
				       + " bytes; Expected " + contentLength + " bytes");
				    }
				    
				    
				    outputStream.write(data);
				    outputStream.flush();
					outputStream.close();
					} catch (Exception e) {
						logger.error(e);
					}
					
					// END RECUPERO FILE REMOTO E SALVATAGGIO TEMPORANEO IN LOCALE
					
					File f=new File(contextPath+"/"+fileName);
					
					wr=new WordReader(f, text);
					
					searchedTextIndex = wr.search();
					
					
					if(searchedTextIndex>0){
						candidatoDTO.getWordSearchDTO().setSearchPosition(""+searchedTextIndex);
						returnValue.add(candidatoDTO);
					}
					
					f.delete();
			}
			
		}		
		
		logger.info("END - CandidatoFacade - ricercaSuFile "+returnValue.size());
		
		return returnValue;
	}

}
